const Promise = require('bluebird');

/**
 * 自动代理结算
 */
exports.autoSettle = function ({}, {models: {TaokeOrders, AgencysSettles}}) {
    return TaokeOrders.agencyBatchSettleV2(false, 1).then(function () {
        return AgencysSettles.batchAmountV2();
    });
}

/**
 * 自动入账
 */
exports.autoAmount = function ({}, {models: {TaokeOrders}}) {
  console.log('===autoAmount');
    return TaokeOrders.findAll({where:{payStatus:['订单付款', '订单结算'], is_amount: 0, created_at: {$gte: '2019-06-28 00:00:00'}}}).then((orders)=>{
      console.log('===autoAmount', orders);
      return Promise.mapSeries(orders, function(order){
          return TaokeOrders.amountV2(order.id);
        });
    });
}

/**
 * 更新用户标签
 */
let updateing = false;
exports.updateWechatTags = function ({query}, {models: {Users}, cache: {dicts}, wechatInstance}) {
    if (updateing) {
        return {success: false, message: '正在更新中，不要重复执行'};
    }
    updateing = true;

    return Users.findAll({where: {level: 'Partner'}, raw: true}).then(function (users) {
        return Promise.mapSeries(users, function (user) {
            let limit = 50, where = {partner_id: user.id};
            let handler = function () {
                return Users.findAll({
                    where: where,
                    limit: limit,
                    attributes: ['id', 'openid'],
                    order: [['id', 'desc']],
                    raw: true
                }).then(function (userList) {
                    let dictValue = dicts.text('user_tag', user.id);
                    if (dictValue) {
                        let tagId = dictValue.split('_')[1];
                        if (tagId) {
                            return new Promise(function (resolve) {
                                let openids = [];
                                for (let i in userList) {
                                    openids.push(userList[i].openid);
                                }
                                wechatInstance.shopWebApi.membersBatchtagging(tagId, openids, function (err, result) {
                                    if (err) {
                                        console.error('\n', err.stack || err.message);
                                    }
                                    console.log(tagId, openids, result);
                                    resolve();
                                });
                            }).then(function () {
                                if (userList.length == limit) {
                                    where.id = {$lt: userList[limit - 1].id};
                                    return handler();
                                }
                                return {success: true};
                            });
                        }
                    }
                });
            }
            return handler();
        }).then(function () {
            let dictValue = dicts.text('user_tag', 'agency');
            if (dictValue) {
                let tagId = dictValue.split('_')[1];
                if (tagId) {
                    let limit = 50, where = {level: 'Agency'};
                    let handler = function () {
                        return Users.findAll({
                            where: where,
                            limit: limit,
                            attributes: ['id', 'openid'],
                            order: [['id', 'desc']],
                            raw: true
                        }).then(function (userList) {
                            return new Promise(function (resolve) {
                                let openids = [];
                                for (let i in userList) {
                                    openids.push(userList[i].openid);
                                }
                                wechatInstance.shopWebApi.membersBatchtagging(tagId, openids, function (err, result) {
                                    if (err) {
                                        console.error('\n', err.stack || err.message);
                                    }
                                    console.log(tagId, openids, result);
                                    resolve();
                                });
                            }).then(function () {
                                if (userList.length == limit) {
                                    where.id = {$lt: userList[limit - 1].id};
                                    return handler();
                                }
                                return {success: true};
                            });
                        });
                    }
                    return handler();
                }
            }
        });
    }).then(function () {
        updateing = false;
        return {success: true};
    }).catch(function (err) {
        if (err) {
            console.error('\n', err.stack || err.message);
        }

        updateing = false;
        return {success: false};
    });
}
